const {
	app,
	ipcMain,
	BrowserWindow,
	desktopCapturer
} = require('electron');
const Store = require('electron-store');
const CaptureView = require('./electron-captureview/main/captureview').default;
const path = require('path');
const https = require('https');
const url = require('url');
// const TimMain = require('im_electron_sdk/dist/main');
const {
	SDK_APP_ID
} = require('./const/const');
const IPC = require('./ipc');
// const CallWindowIpc = require('./callWindowIpc');
// const ChatWindowIpc = require('./chatWindowIpc');
// const CallWindowIpcbak = require('./callWindowIpcbak');
const electron = require('electron');
const tray = require('./tray');
const store = new Store();
Store.initRenderer();
const fs = require('fs-extra')
const fs1 = require('fs');

const Tray = electron.Tray;
const {
	autoUpdater
} = require("electron-updater");
let callWindowIpc;
let chatWindowIpc;
let callWindowIpcbak;
let ipc;
let mainInstance;
let catchedSdkAppId;
const settingConfig = store.get('setting-config');
const sdkappid = catchedSdkAppId = settingConfig?.sdkappId ?? SDK_APP_ID;

const initTimMain = (appid) => {
	mainInstance = new TimMain({
		sdkappid: appid
	});
}
// 在 app 初始化之前添加命令行开关
app.commandLine.appendSwitch('--enable-features', 'PlatformHEVCDecoderSupport');
// initTimMain(sdkappid);

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

ipcMain.handle('re-create-main-instance', async (event, newSdkAppid) => {
	console.log("************ re-create-main-instance", newSdkAppid)
	if (newSdkAppid !== catchedSdkAppId) {
		catchedSdkAppId = newSdkAppid;
		mainInstance.destroy();
		await initTimMain(newSdkAppid);
	}

	await sleep(1000)
	return
})

const {
	crashReporter
} = require('electron')
const logger = require('electron-log');
crashReporter.start({
	submitURL: 'https://888.yafangwanhui.com/api/yfappnew/pcErrorLog'
})


// This allows TypeScript to pick up the magic constant that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
// declare const MAIN_WINDOW_WEBPACK_ENTRY: string;

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// app.on('window-all-closed', function () {
//   if (process.platform !== 'darwin') app.quit()
// })
let mainWindow = null;
const createWindow = () => {
	// Create the browser window.
	mainWindow = new BrowserWindow({
		width: 1000,
		height: 750,
		minWidth: 850,
		minHeight: 600,
		show: false,
		// frame: false,// 隐藏原生标题栏
		webPreferences: {
			webSecurity: false,
			nodeIntegration: true,
			nodeIntegrationInWorker: true,
			enableRemoteModule: true,
			contextIsolation: false,
		}
	});
	mainWindow.setMenuBarVisibility(false); // 隐藏菜单栏
	global.WIN = mainWindow;
	process.on('uncaughtException', function (error) {
		// const data = JSON.stringify(error)		 
		// const options = {
		// 	hostname: 'test.yafang888.com',
		// 	port: 80,
		// 	path: '/api/yfappnew/pcErrorLog',
		// 	method: 'POST',
		// 	headers: {
		// 		'Content-Type': 'application/json',
		// 		'Content-Length': data.length
		// 	}
		// }
		// const req = https.request(options, req => {})
		// req.end()
	})
	ipcMain.on('news', function () { //news 是自定义的命令 ，只要与页面发过来的命令名字统一就可以
		//接收到消息后的执行程序
		console.log('闪烁');
	})

	process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
	/*mainWindow.on('close', () => {
	  mainWindow.webContents.send('updateHistoryMessage');
	  console.log(333)
	  /!*setTimeout(() => {
		app.exit();
	  }, 30);*!/
	});*/
	console.log('======process env======', process.env?.NODE_ENV);
	if (process.env?.NODE_ENV?.trim() === 'development') {
		mainWindow.loadURL(`http://localhost:3000/`);
		mainWindow.webContents.openDevTools();
	} else {
		mainWindow.loadURL(
			url.format({
				pathname: path.join(__dirname, '../client/dist/index.html'),
				protocol: 'file:',
				slashes: true
			})
		);
		// mainWindow.webContents.openDevTools();
	}
	mainWindow.on('ready-to-show', () => {
		mainWindow.show();
		if (!ipc) ipc = new IPC(mainWindow);
		// //关闭语音通话
		// if (!callWindowIpc) {
		// 	callWindowIpc = new CallWindowIpc();
		// }
		// if (!chatWindowIpc) {
		// 	chatWindowIpc = new ChatWindowIpc();
		// }
		// if (!callWindowIpcbak) {
		// 	callWindowIpcbak = new CallWindowIpcbak();
		// }
		tray(mainWindow);
	});
	const capture = new CaptureView({
		devTools: false,
		Mosaic: false,
		Text: false,
		onShow: () => {
			console.log('启动截图')
		},
		onClose: () => {
			//  const png = clipboard.readImage().toBitmap();
			//  const fileExample = new File([png], 'xxx.png', { type: 'image/jpeg' });
			// console.log('结束截图', fileExample);
		},
		onShowByShortCut: () => {
			console.log('快捷键启动截图')
		}
	});
	capture.setMultiScreen(true);
	capture.updateShortCutKey('shift+option+c');
	//mainWindow.loadURL(`http://localhost:3000`);
	//mainWindow.webContents.openDevTools();

	//执行自动更新检查
	//const feedUrl = `https://888.yafangwanhui.com/yafangpckh/`; // 更新包位置
	const feedUrl = `https://cdn.yafangwanhui.com/yafangpc/`; // 更新包位置


	// 更新前，删除本地安装包 ↓
	let updaterCacheDirName = 'electron-admin-updater'
	const updatePendingPath = path.join(autoUpdater.app.baseCachePath, updaterCacheDirName, 'pending')
	fs.emptyDir(updatePendingPath)
	// 本地开发环境，改变app-update.yml地址
	if (process.env.NODE_ENV === 'development') {
		autoUpdater.updateConfigPath = path.join(__dirname, '../../dist/win-unpacked/resources/app-update.yml')
		// autoUpdater.updateConfigPath = path.join(__dirname, '../../dist/win-unpacked/resources/app.yml')
	} else {
		// autoUpdater.updateConfigPath = path.join(__dirname, '../../resources/app-update.yml')
	}
	autoUpdater.setFeedURL(feedUrl);
	let message = {
		error: '检查更新出错',
		checking: '正在检查更新……',
		updateAva: '检测到新版本，正在下载……',
		updateNotAva: '现在使用的就是最新版本，不用更新',
	};
	autoUpdater.on('error', function (error) {
		/*    console.log(error,2221)
			  sendUpdateMessage(autoUpdater.updateConfigPath)
			  sendUpdateMessage(autoUpdater)
			sendUpdateMessage(error)*/
		const time = new Date()
		sendUpdateMessage(message.error)
		// fs1.appendFile("./updateerr.txt", `,${time}:${message.error}`, (err) => {
		// 	if (err) {
		// 		console.log(err);
		// 	} else {
		// 		console.log("追加成功");
		// 	}
		// })
	});
	autoUpdater.on('checking-for-update', function () {
		sendUpdateMessage(message.checking)
	});
	autoUpdater.on('update-available', function (info) {
		sendUpdateMessage("startdown")
	});
	autoUpdater.on('update-not-available', function (info) {
		sendUpdateMessage(message.updateNotAva)
	});

	// 更新下载进度事件
	autoUpdater.on('download-progress', function (progressObj) {
		mainWindow.webContents.send('downloadProgress', progressObj)
		//mainWindow.setProgressBar(progressObj.percent / 100);
	})
	autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl,
		quitAndUpdate) {
		/*const req = https.request(feedUrl+'info.txt', req => {
		  let detail = ''
		  req.setEncoding('utf-8')
		  req.on('data', chunk => {
			detail += chunk.toString()
		  })
		  req.on('end', () => {
			  dialog.showMessageBox({
				  icon: __dirname + '/static/yflogo.png',
				  type: 'info',
				  title: '软件更新',
				  message: `已更新到最新版本（${event.version}）请重启应用。`,
				  detail: detail,
				  buttons: ['确定']
			  }).then((index) => {
				  if (index.response === 0) {
					  autoUpdater.quitAndInstall();
				  }
			  });
		  })
		})
		req.end()*/
		ipcMain.on('isUpdateNow', (e, arg) => {
			// console.log(e);
			autoUpdater.quitAndInstall();
		});
		mainWindow.webContents.send('isUpdateNow')
	});

	ipcMain.on("checkForUpdate", () => {
		//执行自动更新检查
		autoUpdater.checkForUpdates();
	})

	function sendUpdateMessage(text) {
		mainWindow.webContents.send('message', text)
	}

};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
//app.on('ready', createWindow);
// app.on('ready', async () => {
// 	createWindow()
// 	require('@electron/remote/main').initialize()
// })
app.on('ready', () => {
	const gotTheLock = app.requestSingleInstanceLock();
	if (!gotTheLock) {
		app.quit();
	} else {
		createWindow();
		app.on('second-instance', () => {
			if (mainWindow.isVisible()) {
				if (mainWindow.isMinimized()) {
					mainWindow.restore()
					mainWindow.show()
				} else {
					mainWindow.show()
				}
			} else {
				mainWindow.show()
			}
		});
	}
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
/*app.on('window-all-closed', () => {
  console.log('all-window-closed');
  if (process.platform !== 'darwin') {
	app.exit();
  }
});*/

app.on('activate', () => {
	// On OS X it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (BrowserWindow.getAllWindows().length === 0) {
		createWindow();
	}
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.



// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
